import tkinter as tk
from tkinter import filedialog, ttk, messagebox
import os
import pathlib
import re

class ImageRenamerApp:
    def __init__(self, root):
        self.root = root
        self.root.title("图片批量重命名工具")
        self.root.geometry("700x500")
        self.root.resizable(True, True)
        
        # 设置字体和样式
        self.style = ttk.Style()
        self.style.configure("TButton", font=("微软雅黑", 10))
        self.style.configure("TLabel", font=("微软雅黑", 10))
        self.style.configure("Header.TLabel", font=("微软雅黑", 12, "bold"))
        
        # 创建主框架
        self.main_frame = ttk.Frame(root, padding="20")
        self.main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 标题
        ttk.Label(
            self.main_frame, 
            text="图片批量重命名工具", 
            style="Header.TLabel"
        ).pack(pady=(0, 20))
        
        # 创建按钮区域
        self.buttons_frame = ttk.Frame(self.main_frame)
        self.buttons_frame.pack(fill=tk.X, pady=(0, 20))
        
        # 主图按钮
        self.main_btn = ttk.Button(
            self.buttons_frame, 
            text="选择并重命名主图", 
            command=self.process_main_files
        )
        self.main_btn.pack(side=tk.LEFT, padx=(0, 10))
        
        # 详情图按钮
        self.detail_btn = ttk.Button(
            self.buttons_frame, 
            text="选择并重命名详情图", 
            command=self.process_detail_files
        )
        self.detail_btn.pack(side=tk.LEFT, padx=(0, 10))
        
        # SKU图按钮
        self.sku_btn = ttk.Button(
            self.buttons_frame, 
            text="选择并重命名SKU图", 
            command=self.process_sku_files
        )
        self.sku_btn.pack(side=tk.LEFT)
        
        # 状态标签
        self.status_label = ttk.Label(
            self.main_frame, 
            text="请选择要处理的图片类型", 
            foreground="blue"
        )
        self.status_label.pack(anchor=tk.W, pady=(0, 10))
        
        # 进度条
        self.progress_var = tk.DoubleVar()
        self.progress_bar = ttk.Progressbar(
            self.main_frame, 
            variable=self.progress_var, 
            length=100, 
            mode='determinate'
        )
        self.progress_bar.pack(fill=tk.X, pady=(0, 10))
        
        # 日志区域
        ttk.Label(self.main_frame, text="操作日志:").pack(anchor=tk.W)
        
        self.log_frame = ttk.Frame(self.main_frame)
        self.log_frame.pack(fill=tk.BOTH, expand=True)
        
        # 滚动条
        self.scrollbar = ttk.Scrollbar(self.log_frame)
        self.scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # 日志文本框
        self.log_text = tk.Text(
            self.log_frame, 
            wrap=tk.WORD, 
            yscrollcommand=self.scrollbar.set,
            height=10,
            font=("微软雅黑", 9)
        )
        self.log_text.pack(fill=tk.BOTH, expand=True)
        self.scrollbar.config(command=self.log_text.yview)
        
        # 使文本框不可编辑
        self.log_text.config(state=tk.DISABLED)
    
    def log(self, message):
        """向日志文本框添加消息"""
        self.log_text.config(state=tk.NORMAL)
        self.log_text.insert(tk.END, message + "\n")
        self.log_text.see(tk.END)  # 滚动到最后
        self.log_text.config(state=tk.DISABLED)
        self.root.update_idletasks()  # 更新界面
    
    def update_status(self, message):
        """更新状态标签"""
        self.status_label.config(text=message)
        self.root.update_idletasks()
    
    def update_progress(self, value):
        """更新进度条"""
        self.progress_var.set(value)
        self.root.update_idletasks()
    
    def process_files(self, file_type, prefix, replace_words):
        """处理文件的通用方法"""
        try:
            # 打开文件选择对话框
            self.update_status(f"正在选择{file_type}文件...")
            files = filedialog.askopenfilenames(
                initialdir=os.getcwd(),
                title=f"选择{file_type}文件",
                filetypes=[("所有图片文件", "*.jpg;*.png;*.gif;*.webp;*.jpeg")]
            )
            
            if not files:
                self.update_status(f"未选择任何{file_type}文件")
                return
            
            files = list(files)
            total_files = len(files)
            self.update_status(f"正在处理{total_files}个{file_type}文件...")
            self.update_progress(0)
            
            # 尝试排序文件
            try:
                files.sort(key=lambda item: int(re.search(r"\d+", pathlib.Path(item).resolve().stem).group()))
                self.log(f"已按数字顺序排序{total_files}个{file_type}文件")
            except Exception as e:
                self.log(f"排序警告: 无法按数字排序，将使用默认顺序 - {str(e)}")
            
            # 重命名文件
            success_count = 0
            for index, file in enumerate(files, start=1):
                try:
                    file_path = pathlib.Path(file).resolve()
                    directory = file_path.parent
                    old_name = file_path.name
                    suffix = file_path.suffix
                    
                    # 创建新文件名
                    new_basename = f"{prefix}-{index:03}"
                    for word in replace_words:
                        new_basename = new_basename.replace(word, "-")
                    new_name = f"{new_basename}{suffix}"
                    
                    # 重命名
                    old_full_path = os.path.join(directory, old_name)
                    new_full_path = os.path.join(directory, new_name)
                    
                    os.rename(old_full_path, new_full_path)
                    self.log(f"已重命名: {old_name} -> {new_name}")
                    success_count += 1
                    
                except Exception as e:
                    self.log(f"重命名失败 {old_name}: {str(e)}")
                
                # 更新进度
                progress = (index / total_files) * 100
                self.update_progress(progress)
            
            self.update_progress(100)
            self.update_status(f"{file_type}处理完成: 成功{success_count}个，失败{total_files - success_count}个")
            messagebox.showinfo("完成", f"{file_type}处理完成:\n成功{success_count}个\n失败{total_files - success_count}个")
            
        except Exception as e:
            error_msg = f"处理{file_type}时出错: {str(e)}"
            self.update_status(error_msg)
            self.log(error_msg)
            messagebox.showerror("错误", error_msg)
    
    def process_main_files(self):
        """处理主图文件"""
        self.process_files(
            "主图", 
            "Main", 
            ["主", "图", "首"]
        )
    
    def process_detail_files(self):
        """处理详情图文件"""
        self.process_files(
            "详情图", 
            "Detail", 
            ["详情", "长图"]
        )
    
    def process_sku_files(self):
        """处理SKU图文件"""
        self.process_files(
            "SKU图", 
            "SKU", 
            ["规格", "属性"]
        )

if __name__ == "__main__":
    root = tk.Tk()
    app = ImageRenamerApp(root)
    root.mainloop()
